package com.diamond.webservice.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.commons.lang3.StringUtils;

/**
 * 访问工具
 */
public class ConnectionHelper {
    private static Logger logger = LoggerFactory.getLogger(ConnectionHelper.class);
    private static final String DEFAULT_ENCODING = "UTF-8";
    public static String baseUrl = "http://10.72.30.111:10011/dzzzinte/jtCommon/archive/system";
    protected static final String regx = ".*logout.*";
    protected static final String regx1 = ".*login.*";
    protected static final String regx2 = ".*license/.*/.*";
    protected static final String regx3 = ".*license.*";

    /**
     * 模拟Http协议,发送请求,将网页以流的形式读回来
     * @param url
     * @param method
     * @param data
     */
    public static String HttpConnect(String url, String method ,String data) {
        StringBuilder result = new StringBuilder();
        if(url.matches(regx)){
            String urllogout = url.substring(url.indexOf("security/") + 9, url.indexOf("?"));
            logger.info("正在执行 [{}] 接口···", urllogout.toUpperCase());
        } else if(url.matches(regx1)) {
            String urllogin = url.substring(url.indexOf("security/") + 9 );
            logger.info("正在执行 [{}] 接口···", urllogin.toUpperCase());
        } else if(url.matches(regx2)) {
            String urllicense = url.substring(url.indexOf("license/") + 8, url.indexOf("?"));
            String urllicense1 = urllicense.substring(urllicense.indexOf("/") + 1);
            logger.info("正在执行 [{}] 接口···", urllicense1.toUpperCase());
        } else if(url.matches(regx3)) {
            String urllicense2 = url.substring(url.indexOf("license/") + 8, url.indexOf("?"));
            logger.info("正在执行 [{}] 接口···", urllicense2.toUpperCase());
        }
        try {
            //创建一个URL对象
            URL httpurl = new URL(url);
            long s = System.currentTimeMillis();
            HttpURLConnection hc = (HttpURLConnection) httpurl.openConnection();
            //设置连接超时(毫秒)
            hc.setConnectTimeout(6 * 1000);
            String Method = method.toUpperCase();
            if("GET".equals(Method)) {
                logger.debug("get request url: " + url );
                logger.debug("get request data: " + data);
            }
            logger.debug("Method: " + Method);
            //设置提交方式get或者post
            hc.setRequestMethod(Method);
            //URL 连接可用于输入和/或输出。将 doInput 标志设置为 true，指示应用程序要从 URL 连接读取数据。
            hc.setDoInput(true);
            if("POST".equals(Method)) {
                //post请求一定要容许输出
                hc.setDoInput(true);
                hc.setDoOutput(true);
                if(data != null) {
                    //设置文件的总长度
                    hc.setRequestProperty("Content-Length",
                            String.valueOf(data.length()));
                }
            }
            //设置缓存
            hc.setUseCaches(false);
            //设置文件类型
            hc.setRequestProperty("Content-Type", "application/json");
            //设置字符集
            hc.setRequestProperty("Charset", "utf-8");
            //连接
            hc.connect();
            if("POST".equals(Method)) {
                OutputStream ops = hc.getOutputStream();
                byte [] buff;
                if(data != null){
                    //设置请求参数为二进制流为UTF-8编码格式
                    buff = data.getBytes(DEFAULT_ENCODING);
                    ops.write(buff);
                }
                ops.flush();//刷空输出流，并输出所有被缓存的字节
                ops.close();//流操作完毕后关闭
            }
            //请求响应代码
            logger.info("Http Status Code:" + hc.getResponseCode());
            //请求头文件
            logger.info("request headers : " + hc.getHeaderFields());
            int code = hc.getResponseCode();
            if(code == 200) {
                InputStream ins;
                ins = hc.getInputStream();
                //将返回的字节流转换为字符流
                InputStreamReader isr = new InputStreamReader(ins, DEFAULT_ENCODING);
                char[] cbuf = new char[1024];
                int i = isr.read(cbuf);
                while (i > 0) {
                    result.append(new String(cbuf, 0 ,i));
                    i = isr.read(cbuf);
                }
                ins.close();

            } else {
                logger.error("连接发生错误，错误代码：" + code);
                InputStream ins;
                ins = hc.getErrorStream();
                InputStreamReader isr = new InputStreamReader(ins);
                char [] cbuf = new char[1024];
                int i = isr.read(cbuf);
                while(i > 0) {
                    result.append(new String(cbuf, 0, i));
                    i = isr.read(cbuf);
                }
                logger.debug("error:" + result);
                //关闭输出流
                ins.close();
            }

            //关闭请求
            hc.disconnect();
            long e = System.currentTimeMillis();
            long time = e - s;
            logger.info("耗时: " + time + "毫秒");
        } catch (Exception e) {
            logger.debug("", e.fillInStackTrace());
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * 模拟https安全协议
     * @param url
     * @param data
     * @param method
     */
    public static String HttpsConnect(String url , String method, String data) {
        StringBuilder result = new StringBuilder();
        if(url.matches(regx)){
            String urllogout = url.substring(url.indexOf("security/") + 9, url.indexOf("?"));
            logger.info("正在执行 [{}] 接口···", urllogout.toUpperCase());
        } else if(url.matches(regx1)) {
            String urllogin = url.substring(url.indexOf("security/") + 9 );
            logger.info("正在执行 [{}] 接口···", urllogin.toUpperCase());
        } else if(url.matches(regx2)) {
            String urllicense = url.substring(url.indexOf("license/") + 8, url.indexOf("?"));
            String urllicense1 = urllicense.substring(urllicense.indexOf("/") + 1);
            logger.info("正在执行 [{}] 接口···", urllicense1.toUpperCase());
        } else if(url.matches(regx3)) {
            String urllicense2 = url.substring(url.indexOf("license/") + 8, url.indexOf("?"));
            logger.info("正在执行 [{}] 接口···", urllicense2.toUpperCase());
        }
        try {
            //创建一个请求对象
            URL httpsurl = new URL(url);
            long s = System.currentTimeMillis();
            HttpsURLConnection hsc = (HttpsURLConnection) httpsurl.openConnection();
            X509TrustManager xtm = new MyX509TrustManager();
            X509TrustManager [] mytm = new X509TrustManager [] { xtm };

            SSLContext sct = SSLContext.getInstance("SSL");
            sct.init(null, mytm, null);
            MyHostnameVerifier hostnameVerifier = new MyHostnameVerifier();
            hsc.setHostnameVerifier(hostnameVerifier);
            hsc.setSSLSocketFactory(sct.getSocketFactory());

            String Method = method.toUpperCase();
            if("GET".equals(Method)) {
                logger.debug("get request url:" + url);
                logger.debug("get request data:" + url);
            }
            logger.debug("Method:" + Method);
            hsc.setRequestMethod(Method);
            hsc.setDoInput(true);
            if("POST".equals(Method)) {
                hsc.setDoInput(true);
                hsc.setDoOutput(true);
                if(data != null) {
                    hsc.setRequestProperty("Content-Length",
                            String.valueOf(data.length()));
                }
            }
            hsc.setRequestProperty("Content-Type", "application/json");
            hsc.setRequestProperty("Charset", DEFAULT_ENCODING);

            hsc.connect();
            if("POST".equals(Method)) {
                OutputStream ops = hsc.getOutputStream();
                byte [] buff;
                if(data != null) {
                    //请求参数为UTF-8格式
                    buff = data.getBytes(DEFAULT_ENCODING);
                    ops.write(buff);
                }
                ops.flush();
                ops.close();
            }
            //请求响应代码
            logger.info("Https Status Code :" + hsc.getResponseCode());
            //请求头文件
            logger.info("request headers : " + hsc.getHeaderFields());
            int code = hsc.getResponseCode();
            if(code == 200) {
                InputStream ins = hsc.getInputStream();
                if(ins.available() < 0) {
                    logger.error("没有响应数据，可能是对方已经断开连接···");
                } else {
                    InputStreamReader isr = new InputStreamReader(ins, DEFAULT_ENCODING);
                    char [] cbuf = new char[1024];
                    int i = isr.read(cbuf);
                    while (i > 0) {
                        result.append(new String(cbuf, 0, i));
                        i = isr.read(cbuf);
                    }
                }
                ins.close();
            } else {
                logger.error("连接发生错误，错误代码：" + code);
                InputStream ins;
                ins = hsc.getErrorStream();
                InputStreamReader isr = new InputStreamReader(ins, DEFAULT_ENCODING);
                char [] cbuf = new char [1024];
                int i = isr.read(cbuf);
                while (i > 0) {
                    result.append(new String(cbuf, 0, i));
                    i = isr.read(cbuf);
                }
                logger.debug("error:" + result);
                ins.close();
            }
            hsc.disconnect();
            long e = System.currentTimeMillis();
            long time = e - s;
            logger.debug("耗时:" + time + "毫秒");
        } catch (Exception e) {
            logger.debug("", e.fillInStackTrace());
            e.printStackTrace();
        }
        return result.toString();
    }

    /**
     * 	定义区分https和http协议的请求
     *
     * @param url
     * @param method
     * @param data
     */
    public static String Connect(String url, String method, String data) {
        if(StringUtils.isNoneBlank(url) && StringUtils.isNoneBlank(method)) {
            if(url.toLowerCase().startsWith("http:")) {
                return HttpConnect(url, method, data);
            } else if(url.toLowerCase().startsWith("https:")) {
                return HttpsConnect(url, method, data);
            }
        }
        return "url or method parameter error···";
    }

    /**
     * 模拟POST请求
     * @param url
     * @param data
     *
     */
    public static String doPost(String url, String data) {
        logger.debug(" post request url : " + url);
        logger.debug("post request data : " + data);
        if(!StringUtils.isNotBlank(data)) {
            data = "{}";
        }
        return Connect(url, "POST", data);
    }
}
